package ar.com.solidussource.howmuchmobile.activities.search;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import ar.com.solidussource.howmuchmobile.R;
import ar.com.solidussource.howmuchmobile.activities.filter.CurrentFilter;
import ar.com.solidussource.howmuchmobile.activities.generic.BaseActivity;
import ar.com.solidussource.howmuchmobile.activities.maps.HowMuchMapActivity;
import ar.com.solidussource.howmuchmobile.common.entities.Address;
import ar.com.solidussource.howmuchmobile.common.entities.Geopoint;
import ar.com.solidussource.howmuchmobile.common.entities.Location;

public class LocationActivitySearch extends BaseActivity implements Runnable {
	private String CONUNTRY = " argentina";
	private Address[] data;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		showProgressDialog();
        process();
	}

	private void doMySearch(String query) {
		HttpClient httpClient = new DefaultHttpClient();
		String encode = "";
		try {
			encode = java.net.URLEncoder.encode(query + CONUNTRY, "UTF-8");
		} catch (UnsupportedEncodingException e) {

		}

		HttpGet del = new HttpGet(
				"http://maps.googleapis.com/maps/api/geocode/json?address="
						+ encode + "&sensor=false");

		del.setHeader("content-type", "application/json");

		try {
			HttpResponse resp = httpClient.execute(del);
			String respStr = EntityUtils.toString(resp.getEntity());

			// JSONArray respJSON = new JSONArray(respStr);
			JSONObject jsonObject = new JSONObject(respStr);
			JSONArray jsonArray = jsonObject.getJSONArray("results");
			data = new Address[jsonArray.length()];
			List<JSONObject> lst = new ArrayList<JSONObject>();
			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject obj = jsonArray.getJSONObject(i);
				data[i] = new Address();
				data[i].setDescription((String) obj.get("formatted_address"));
				JSONObject geometry = (JSONObject) obj.get("geometry");
				JSONObject location = (JSONObject) geometry.get("location");
				Double longitude = (Double) location.get("lng");
				Double latitude = (Double) location.get("lat");
				data[i].setGeopoint(new Geopoint(latitude, longitude));
				lst.add(obj);
			}

		} catch (Exception ex) {
			Log.e("ServicioRest", "Error!", ex);
		}
	}

	private void process(){
        new Thread(this).start();
    }
	
	@Override
	public void run() {
		Intent intent = getIntent();
		if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
			String query = intent.getStringExtra(SearchManager.QUERY);
			doMySearch(query);
		}		
		 handler.sendEmptyMessage(0);
	}
	private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            hideProgressDialog();
            build();
        }
    };
    
    private void build(){
        LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View v = (View) inflater.inflate(R.layout.list_gen_paginated, null);

        LocationArrayAdapter adaptador = new LocationArrayAdapter(this);

        ListView lstOpciones = (ListView)v.findViewById(R.id.menuList);

        lstOpciones.setAdapter(adaptador);
        lstOpciones.setOnItemClickListener(new ProvinceOnItemClickListener());

        setContent(v);
    }
    
    class LocationArrayAdapter extends ArrayAdapter<Address> {

        Activity context;

        LocationArrayAdapter(Activity context) {
            super(context, R.layout.list_gen_row, data);
            this.context = context;
        }

        @Override
		public View getView(int position, View convertView, ViewGroup parent) {
            LayoutInflater inflater = context.getLayoutInflater();
            View item = inflater.inflate(R.layout.list_gen_row, null);

            TextView lblTitulo = (TextView)item.findViewById(R.id.row);
            lblTitulo.setText(data[position].getDescription());

            return(item);
        }

    }

    class ProvinceOnItemClickListener implements AdapterView.OnItemClickListener {

        @Override
		public void onItemClick(AdapterView<?> a, View v, int position, long id) {
        	Address add = data[position];
        	CurrentFilter.setLocation(new Location(add.getGeopoint()));
        	Intent intent = new Intent(LocationActivitySearch.this, HowMuchMapActivity.class);
            startActivity(intent);
			/*Intent myIntent = new Intent(LocationActivitySearch.this,
					HowMuchMap.class);
			myIntent.putExtra("latitude", latitude);
			myIntent.putExtra("longitude", longitude);
			LocationActivitySearch.this.startActivity(myIntent);*/
			
        	/*Intent intent = new Intent(Provinces.this, Locations.class);
            intent.putExtra("provinceId", data[position].getId());
            //intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
            startActivity(intent);*/
        }

    }

}
